﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BugTracker.Models;
using BugTracker.Helper;
using System.Data;
using System.Security;
using System.Configuration;
using System.Web.Security;

namespace BugTracker.Controllers
{
    public class HomeController : Controller
    {
        // Database Declaration

        Bug_db toget = new Bug_db();
        SessionHelper sessionhelper = new SessionHelper();
        Role roles = new Role();
        ErrorLogHelpers bug_errorlog = new ErrorLogHelpers();

        #region Variable Declarations

        private int userID;
        static string name;
        public string errmessage;
        private readonly Random _rng = new Random();
        private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        #endregion

        //
        // GET: /LogIn/
        #region public ActionResult Login (string msg)
        public ActionResult Login(string msg)
        {
            string msge = Request.QueryString["msg"];
            if (msge == "expired")
            {
                ViewBag.Error = "Your session has expired or someone has on your account";

            }

            if (sessionhelper.Session_Info() != null)
            {
                if (sessionhelper.Session_Info().session_flag == 0)
                {
                    return View();
                }
                if (sessionhelper.SessionAuth(sessionhelper.Session_Info().session_idPK) == true)
                {
                    if (sessionhelper.Session_GetRole() == "Administrator")
                    {
                        return RedirectToAction("Index", "Admin");
                    }

                    else if (sessionhelper.Session_GetRole() == "Developer")
                    {
                        return RedirectToAction("Home", "Developer");
                    }
                    else if (sessionhelper.Session_GetRole() == "Quality Assurance")
                    {
                        return RedirectToAction("Home", "Quality Assurance");
                    }
                    if  (sessionhelper.Session_GetRole() == "Project Manager")
                    {
                        return RedirectToAction("Home", "Project Manager");
                    }
                }
                else
                {
                    return View();
                }
            }
            ViewBag.ErrorMessage = errmessage;
            return View();
        }
#endregion


        //public ActionResult RSSFeeds()
        //{
        //    var g = rssHelper.RSSFeed("http://themoneyconverter.com/PHP/rss.xml");

        //    rssModel.Title = g.Title.Text;
        //    rssModel.Description = g.Description.Text;
        //    rssModel.Link = g.Links;
        //    rssModel.Item = g.Items.ToList();

        //    return View(rssModel);

        //}
        #region HTTPPOST Login
        //[Authorize]
        [HttpPost, ValidateInput(false)]
        public ActionResult Login(FormCollection collection, Session session, User users)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            Response.Cache.SetNoStore();

            string user_name = collection["user_name"].Trim();
            string password = collection["password"].Trim();
            string userBrowser = sessionhelper.Session_GetBrowserType();
            string date = DateTime.Now.ToString("d/MM/yyyy");
            bug_errorlog.userlog = sessionhelper.sesionIDPK("password");
            var errorlog = bug_errorlog.Check_ErrorLog();


            if( errorlog != null)
            {
                if (errorlog.log_attempt >= 3)
                {
                    var checklog = sessionhelper.Session_Info();
                    if (checklog != null)
                    {
                        toget.Entry(checklog).State = EntityState.Deleted;
                        toget.SaveChanges();
                    }

                    ViewBag.ErrorMessage = "Login was multiple";
                    errorlog.error_message = ViewBag.ErrorMessage;
                    toget.Entry(errorlog).State = EntityState.Modified;
                    toget.SaveChanges();
                
                }
            
            
            }
            //validation for credentials

            if (user_name != "" && password != "")
            {
                if (user_name != null && password != null)
                {
                    var check = toget.Users.
                        Where(i => i.user_name == user_name).
                        Where(i => i.password == password).SingleOrDefault();

                    if (check != null)
                    {

                        name = check.user_name + " " + check.password;

                        if (name == null)
                        {
                            ViewBag.Title = false;
                            ViewBag.ErrorMessage = "Invalid Username or Password";
                            bug_errorlog.ErrorLog_Init();
                            if (errorlog != null)
                            {
                                errorlog.log_attempt++;
                                toget.Entry(errorlog).State = EntityState.Modified;
                                toget.SaveChanges();
                            }
                            return View();
                        }

                        //check if user is currently logged

                        string today = sessionhelper.Session_GetDateToday();


                        var u = (from s in toget.Sessions
                                 where s.user_idFK == check.user_idPK
                                 && s.session_datelogout == null
                                 && s.session_flag == 1
                                 && s.session_datecreated == today
                                 && s.session_Name == name
                                 select s).SingleOrDefault();



                        //YES
                        #region create session & redirect
                        if (u == null)
                        {
                            int session_id = sessionhelper.Session_Init(check.user_idPK, password, session);
                            int regtime = 20;
                            userID = session_id;
                            check.user_idPK = session_id;
                            sessionhelper.placeholder_id = session_id;


                            if (sessionhelper.Session_Info().rolename != "Administrator")
                            {
                                if (regtime == Convert.ToInt32(sessionhelper.GetTimeinHr()))
                                {

                                    ViewBag.ErrorMessage = "Session has Expired";
                                    int ses_id = sessionhelper.Session_Info().session_idPK;
                                    var session_log = (from l in toget.Sessions
                                                       where l.session_idPK == ses_id
                                                       select l).SingleOrDefault();
                                    toget.Entry(session_log).State = EntityState.Deleted;
                                    toget.SaveChanges();
                                    return View();
                                }

                            }




                            //else if (sessionhelper.Session_Info().rolename != "Project Manager")
                            //{
                            //    if (regtime == Convert.ToInt32(sessionhelper.GetTimeinHr()))
                            //    {

                            //        ViewBag.ErrorMessage = "Session has Expired";
                            //        int ses_id = sessionhelper.Session_Info().session_idPK;
                            //        var session_log = (from p in toget.Sessions
                            //                           where p.session_idPK == ses_id
                            //                           select p).SingleOrDefault();
                            //        toget.Entry(session_log).State = EntityState.Deleted;
                            //        toget.SaveChanges();
                            //        return View();
                            //    }


                            //}
                            
                            
                       
                        
                            if (errorlog != null)
                            {
                                if (sessionhelper.Session_Info().rolename != "Administrator" && errorlog.log_attempt >= 3)
                                {
                                    ViewBag.errmessage = "Not Admin, exceed 3 login attempts";
                                    errorlog.error_message = ViewBag.ErrorMessage;
                                    toget.Entry(errorlog).State = EntityState.Modified;
                                    toget.SaveChanges();

                                    int ses_id = sessionhelper.Session_Info().session_idPK;
                                    var session_log = (from i in toget.Sessions
                                                       where i.session_idPK == ses_id
                                                       select i).SingleOrDefault();
                                    toget.Entry(session_log).State = EntityState.Deleted;
                                    toget.SaveChanges();
                                    return View();
                                }
                                else
                                {
                                    var deletesession = (from i in toget.ErrorLogs
                                                         where i.browser == errorlog.browser && i.log_attempt >= 3
                                                         && i.datetoday == errorlog.datetoday
                                                         select i).SingleOrDefault();
                                    if (deletesession != null)
                                    {
                                        toget.Entry(deletesession).State = EntityState.Deleted;
                                        toget.SaveChanges();
                                    }
                                }
                            }

                            if (check.role_idFK == 1)
                            {

                                return RedirectToAction("Index", "Admin", new { id = session_id });

                            }

                            else if (check.role_idFK == 2)
                            {
                                if (errorlog != null)
                                {
                                    errorlog.log_attempt = 0;
                                    toget.Entry(errorlog).State = EntityState.Modified;
                                    toget.SaveChanges();
                                }

                                return RedirectToAction("Home", "Developer", new { id = session_id });

                            }

                            else if (check.role_idFK == 3)
                            {
                                if (errorlog != null)
                                {
                                    errorlog.log_attempt = 0;
                                    toget.Entry(errorlog).State = EntityState.Modified;
                                    toget.SaveChanges();
                                }
                                return RedirectToAction("Home", "QA", new { id = session_id });

                            }
                            else
                            {
                                if (errorlog != null)
                                {
                                    errorlog.log_attempt = 0;
                                    toget.Entry(errorlog).State = EntityState.Modified;
                                    toget.SaveChanges();
                                }
                                return RedirectToAction("Home", "ProjectManager", new { id = session_id });
                            }

                        }
                        #endregion

                        #region Check existing session Throw error or Create new session
                        //NO
                        else
                        {
                            if (sessionhelper.Session_Info() != null && u.browser == userBrowser && u.session_token == sessionhelper.sessnid)
                            {
                                if (check.role_idFK == 1)
                                {
                                    return RedirectToAction("Index", "Admin", new { id = sessionhelper.Session_Info().session_idPK });

                                }

                                else if (check.role_idFK == 2)
                                {
                                    return RedirectToAction("Index", "Developer", new { id = sessionhelper.Session_Info().session_idPK });

                                }

                                else if (check.role_idFK == 3)
                                {
                                    return RedirectToAction("Home", "QA", new { id = sessionhelper.Session_Info().session_idPK });

                                }
                                else
                                    return RedirectToAction("Home", "ProjectManager", new { id = sessionhelper.Session_Info().session_idPK });

                            }
                            else
                            {

                                sessionhelper.Session_Logout(u.session_idPK);
                                sessionhelper.Session_Init(check.user_idPK, password, session);

                                if (sessionhelper.Session_ExpireWork() == false)
                                {
                                    if (check.role_idFK == 1)
                                    {
                                        return RedirectToAction("Index", "Admin", new { id = sessionhelper.Session_Info().session_idPK });

                                    }

                                    else if (check.role_idFK == 2)
                                    {
                                        return RedirectToAction("Index", "Developer", new { id = sessionhelper.Session_Info().session_idPK });

                                    }

                                    else if (check.role_idFK == 3)
                                    {
                                        return RedirectToAction("Home", "QA", new { id = sessionhelper.Session_Info().session_idPK });

                                    }
                                    else
                                        return RedirectToAction("Home", "ProjectManager", new { id = sessionhelper.Session_Info().session_idPK });
                                }
                                else
                                {
                                    int ses_id = sessionhelper.Session_Info().session_idPK;
                                    var session_log = (from l in toget.Sessions
                                                       where l.session_idPK == ses_id
                                                       select l).FirstOrDefault();
                                    toget.Entry(session_log).State = EntityState.Deleted;
                                    toget.SaveChanges();
                                    ViewBag.ErrorMessage = "Session has expired, Exceed working hours";
                                    return View();

                                }

                            }

                        }
                        #endregion
                    }
                    else
                    {
                        ViewBag.ErrorMessage = "Invalid Username or Password";
                        return View();
                    }
                }


            }
            ViewBag.ErrorMessage = "Username or Password is empty";
            return View();
        }

        #endregion

        #region logout newly added
        public ActionResult Logout()
        {

            if (sessionhelper.Session_Info() == null)
            {
                return RedirectToAction("Login", "Home");

            }

            var logout = sessionhelper.Session_Info();

            if (logout != null)
            {
                sessionhelper.Session_Logout(logout.session_idPK);
                ViewBag.Logoff = "Successfully Log Off";
                return View();

            }

            return View();

        }


        #endregion



        [HttpPost]
        public ActionResult Logout(Session session)
        {
            if (ModelState.IsValid)
            {
                toget.Entry(session).State = EntityState.Modified;
                session.session_flag = 0;
                session.session_datelogout = DateTime.Now.ToString("d/MM/yyyy");
                session.session_timeExpired = DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                toget.SaveChanges();
                return RedirectToAction("Login", "Home");
            }
            return View(session);
        }


        //#region public ActionResult Dashboard
        //public ActionResult Dashboard(int? id, string dashboard)
        //{
        //    if (id == 0)
        //    {
        //        if (sessionhelper.GetUserID() == false)
        //        {
        //            return RedirectToAction("Index");

        //        }
        //    }

        //    else
        //    {
        //        if (sessionhelper.Session_Info() != null)
        //        {
        //            if (sessionhelper.DebugMode == true)
        //            {
        //                ViewBag.iduser = sessionhelper.Session_Info().user_idFK;
        //                ViewBag.browser = sessionhelper.Session_Info().browser;
        //                ViewBag.role_name = sessionhelper.Session_Info().rolename;
        //                ViewBag.date = sessionhelper.Session_Info().session_datecreated;

        //            }
        //            if (sessionhelper.SessionAuth(sessionhelper.Session_Info().session_idPK) == true)
        //            {

        //                if (sessionhelper.GetSession(sessionhelper.Session_Info().session_idPK))
        //                {

        //                    ViewBag.Date = DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
        //                    ViewBag.user_name = "Welcome" + sessionhelper.Session_Info().session_Name;

        //                }

        //                else
        //                {
        //                    return RedirectToAction("Home");

        //                }


        //            }
        //            else
        //            {
        //                ViewBag.message = "You currently Logged";
        //                return RedirectToAction("Login", "Home");


        //            }


        //        }

        //        else
        //        {
        //            return RedirectToAction("Login", "Home", new { msg = "expired" });

        //        }
        //    }

        //    return View();

        //}



        //#endregion



    }

}
